//
//  YTMainTableViewController.swift
//  Rhythm_SinaWeibo
//
//  Created by Mr.Rhythm on 9/21/15.
//  Copyright © 2015 Mr.Rhythm. All rights reserved.
//

import UIKit

class YTMainTableViewController: UITabBarController {
    
    // MARK: - 监听加号按钮点击事件
    @objc private func composeButtonClick() {
        print("加号按钮被点击", terminator: "")
    }
    
    // MARK: - 加入加号按钮
    private func setupComponseButton() {
        // 添加按钮
        tabBar.addSubview(composeButton)
        
        // 设置按钮数量
        let count = self.childViewControllers.count
        
        // 设置按钮的尺寸
        let width = tabBar.bounds.width / CGFloat(count) - 1
        
        composeButton.frame = CGRectInset(tabBar.bounds, width * 2, 0)
        
        composeButton.addTarget(self, action: "composeButtonClick", forControlEvents: .TouchDown)
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        
        // 注意层次结构
        tabBar.bringSubviewToFront(composeButton)
    }
    
    // MARK: - 加载子控件
    
    private func addChildViewController() {
        addChildViewController(YTHomeTableViewController(), title: "首页", imageName: "tabbar_home")
        addChildViewController(YTMessageTableViewController(), title: "消息", imageName: "tabbar_message_center")
        
        // 添加了一个空的控制器
        addChildViewController(UIViewController())
        
        addChildViewController(YTDiscoverTableViewController(), title: "发现", imageName: "tabbar_discover")
        addChildViewController(YTProfileTableViewController(), title: "我", imageName: "tabbar_profile")
    }
    
    /**
        添加子控件抽取的基类方法
    */
    private func addChildViewController(vc: UIViewController, title: String, imageName: String) {
        // 设置按钮图标颜色
        tabBar.tintColor = UIColor.orangeColor()
        
        vc.title = title
        vc.tabBarItem.image = UIImage(named: imageName)
        
        addChildViewController(UINavigationController(rootViewController: vc))
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        addChildViewController()
        
        setupComponseButton()
    }
    
    // MARK:- 懒加载控件
    private lazy var composeButton: UIButton = UIButton(imageName: "tabbar_compose_icon_add", backImageName: "tabbar_compose_button")

}
